import 'dart:async';
import 'dart:collection';
import 'package:like_chat/dto/friend_model.dart';
import 'package:rxdart/rxdart.dart';

import 'package:like_chat/blocs/bloc_provider.dart';
import 'package:like_chat/dto/history_chat.dart';

class FriendsBloc implements BlocBase {
  List<FriendModel> _list;

  StreamController<List<FriendModel>> _syncController =
      BehaviorSubject<List<FriendModel>>();

  Stream<List<FriendModel>> get outFriendsStream =>
      _syncController.stream;

  FriendsBloc() {
    _list = [];
    Future.delayed(Duration(seconds: 2), () {
      add(FriendModel(
        id: "1001",
        phone: "188662",
        name: "张三",
        note: "小明"
      ));
    });
  }

  void add(FriendModel h) {
    _list.add(h);
    _syncController.sink.add(UnmodifiableListView(_list));
  }

  void addAll(List<FriendModel> lists) {
    _list.addAll(lists);
    _syncController.sink.add(UnmodifiableListView(_list));
  }

  void update(FriendModel h) {

    int index = -1;
    for(int i = 0; i< _list.length; i++) {
      if(_list[i].id == h.id) {
        index = i;
        break;
      }
    }
    if(index != -1) {
      _list.removeAt(index);
      _list.insert(0, h);
    }

    _syncController.sink.add(UnmodifiableListView(_list));
  }

  @override
  void dispose() {
    _syncController.close();
  }
}
